<template>
  <BasicTable id="sortTable" :columns="columns" :data-source="tableData" :scroll="{ x: 1800 }">
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'order'">
        <menu-outlined />
      </template>

      <template v-if="column.dataIndex === 'name'">
        <Tooltip
          :str="record.name"
          textColor="color:#0083FF"
          @click="
            toResourcesLibraryList(record.id, record.resource_type, record.content_type, record.status, record.site_id)
          "
        />
      </template>

      <template v-if="column.dataIndex === 'resource_type'">
        {{ selectValueFormatter(RESOURCE_TYPE, record.resource_type) }}
      </template>

      <template v-if="column.dataIndex === 'content_type'">
        {{ selectValueFormatter(CONTENT_TYPE, record.content_type) }}
      </template>

      <template v-if="column.dataIndex === 'site_name'">
        <Tooltip :str="record.site_name" />
      </template>

      <template v-if="column.key === 'collectOperate'"
        >{{ record.value }}
        <CollectOperate btn-type="link" :row-data="record" :disabled="record.status === 2" />
      </template>

      <template v-if="column.dataIndex === 'update_at'">
        <span v-if="record.update_at && record.update_at != 0">{{ formatToDateTime(record.update_at * 1000) }}</span>
        <span v-else>-</span>
      </template>

      <template v-if="column.dataIndex === 'collect_at'">
        <span v-if="record.collect_at && record.collect_at != 0">{{ formatToDateTime(record.collect_at * 1000) }}</span>
        <span v-else>-</span>
      </template>

      <template v-if="column.dataIndex === 'status'">
        <CollectState :value="record.status" :collect-state="COLLECT_START_STATE" />
      </template>

      <span v-if="column.key === 'operationBar'" class="operation-bar">
        <template v-if="isCollectVisible(record.status)">
          <a-button type="link" @click="handleStopCollect(record.id)">停止采集</a-button>
          <a-divider type="vertical" />
        </template>
        <template v-else>
          <a-button type="link" @click="startOrDisabledHandle(record)">{{
            startOrDisabledBtnText(record.status)
          }}</a-button>
          <a-divider type="vertical" />
        </template>
        <a-button
          type="link"
          @click="
            toResourcesLibraryList(record.id, record.resource_type, record.content_type, record.status, record.site_id)
          "
          >资源库</a-button
        >
        <a-divider type="vertical" />
        <a-button type="link" :disabled="isCollectVisible(record.status)" @click="toEditPage(record.id)">编辑</a-button>
        <a-divider type="vertical" />
        <a-button type="link" :disabled="isCollectVisible(record.status)" @click="handleDeleteCollect(record)"
          >删除</a-button
        >
      </span>
    </template>
  </BasicTable>
  <!-- 禁用启用弹窗 -->
  <ModalView
    title="提示"
    v-model:visible="modalVIsible"
    okText="确定"
    cancelText="取消"
    :width="458"
    @confirm="disableConfirm"
    @cancel="disableCancel"
  >
    <span>{{
      `确定要${currentRecord && currentRecord.status === 2 ? '启用' : '禁用'}该采集资源点吗？`
    }}</span></ModalView
  >
  <!-- 删除弹窗 -->
  <ModalView
    title="提示"
    v-model:visible="deleteVisible"
    okText="确定"
    cancelText="取消"
    :width="458"
    @confirm="deleteConfirm"
    @cancel="deleteCancel"
  >
    <span>确定要删除该采集资源点吗？</span></ModalView
  >
  <!-- 停止采集弹窗 -->
  <ModalView
    title="提示"
    v-model:visible="collectVisible"
    okText="确定"
    cancelText="取消"
    :width="458"
    @confirm="stopConfirm"
    @cancel="stopCancel"
  >
    <span>确定要停止采集吗？</span></ModalView
  >
</template>

<script lang="ts" setup name="ResourcesTable">
import BasicTable from '../../../components/BasicTable.vue'
import Sortable from 'sortablejs'
import Tooltip from '../../../components/Tooltip.vue'
import CollectOperate from '../../../components/collect-operate/index.vue'
import CollectState from '../../../components/CollectState.vue'
import { useRouter } from 'vue-router'
import { computed, onMounted, ref } from 'vue'
import { formatToDateTime } from '@/utils/format'
import {
  RESOURCE_TYPE,
  CONTENT_TYPE,
  COLLECT_START_STATE,
  selectValueFormatter
} from '@/stores/modules/collect-manage/select-data-source'
import { getTableData, tableData } from '../../../hooks/useTable'
import {
  stopCollectFunc,
  startOrDisableStatus,
  deleteResourceSite,
  setStartOrDisableRequestApi,
  setDeleteRequestApi,
  setStopCollectRequestApi
} from '../../../public-handle'
import ModalView from '@/components/components/modal/ModalView.vue'
import { modalVIsible, deleteVisible, collectSourceParams, collectVisible } from '../../../public-handle'
import apis from '@/apis'
import useStore from '@/stores'
import { message } from 'ant-design-vue'
const { collectManage } = useStore()
console.log('collectManage: ', collectManage)
const { updateCollectStatusSingle, deleteCollectSingle, stopCollect, collectOrder } = apis.collectManage
getTableData()
const router = useRouter()

const columns = [
  {
    title: '排序',
    dataIndex: 'order',
    width: 60
  },
  {
    title: '采集资源ID',
    dataIndex: 'id',
    maxWidth: 190
  },
  {
    title: '资源名称',
    dataIndex: 'name'
  },
  {
    title: '资源类型',
    dataIndex: 'resource_type',
    maxWidth: 120
  },
  // {
  //   title: '内容类型',
  //   dataIndex: 'content_type'
  // },
  // {
  //   title: '采到站点',
  //   dataIndex: 'site_name',
  //   width: 200,
  //   ellipsis: true
  // },
  {
    title: '采集操作',
    key: 'collectOperate',
    width: 300
  },
  {
    title: '资源更新时间',
    dataIndex: 'update_at',
    maxWidth: 190
  },
  {
    title: '最近采集时间',
    dataIndex: 'collect_at',
    maxWidth: 190
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 120
  },
  {
    title: '操作',
    key: 'operationBar',
    fixed: 'right',
    width: 260
  }
]

type StatusType = number

// 停止采集
const isCollectVisible = computed(() => (status: StatusType) => status === 3)

// 启用/禁用
const startOrDisabledBtnText = computed(() => (status: StatusType) => {
  switch (status) {
    case 1:
      return '禁用'
    case 2:
      return '启用'
  }
})
const currentRecord = ref()
//禁用
const startOrDisabledHandle = (record: any) => {
  if (record.status === 2) {
    setStartOrDisableRequestApi(updateCollectStatusSingle)
    startOrDisableStatus(record.status, record.id, '采集资源点')
  } else {
    modalVIsible.value = true
    currentRecord.value = record
    setStartOrDisableRequestApi(updateCollectStatusSingle)
  }
}
//禁用确认
const disableConfirm = (value: any) => {
  startOrDisableStatus(currentRecord.value.status, currentRecord.value.id, '采集资源点')
}
//禁用取消
const disableCancel = () => {
  modalVIsible.value = false
}
//删除
const deleteRecord = ref()
const handleDeleteCollect = (record: any) => {
  deleteVisible.value = true
  deleteRecord.value = record
}
//删除确认
const deleteConfirm = (value: any) => {
  //deleteResourceSite(record.id, '采集资源点')
  setDeleteRequestApi(deleteCollectSingle)
  console.log('deleteRecord.value.id: ', deleteRecord.value.id)
  deleteResourceSite(deleteRecord.value.id, '采集资源点')
}
//删除取消
const deleteCancel = () => {
  deleteVisible.value = false
}
// 编辑
const toEditPage = (id: string) => {
  router.push({ name: 'AddEditCollectForm', query: { id } })
}
const stopId = ref()
//停止
const handleStopCollect = (id: string) => {
  collectVisible.value = true
  stopId.value = id
}
//停止采集确认
const stopConfirm = (value: any) => {
  setStopCollectRequestApi(stopCollect)
  stopCollectFunc(stopId.value)
}
//停止采集取消
const stopCancel = () => {
  collectVisible.value = false
}
// 去资源库页面
const toResourcesLibraryList = (
  id: string,
  resource_type: number,
  content_type: number,
  status: number,
  site_id: string
) => {
  Object.assign(collectSourceParams, { id, resource_type, content_type, status, site_id })
  console.log('collectSourceParams: ', collectSourceParams)
  collectManage.$patch((state) => {
    Object.assign(state, { id, resource_type, content_type, status, site_id })
  })
  router.push({ name: 'ResourcesLibraryList', query: { id, resource_type, content_type, status, site_id } })
}
//调用排序接口
const sortFunc = (item: any) => {
  collectOrder({
    ...item
  }).then(() => {
    message.success('排序成功')
    getTableData()
  })
}
//初始化表格拖动
const initSortable = () => {
  const el = document.querySelector('#sortTable tbody') as HTMLElement
  console.log({ el })
  new Sortable(el, {
    handle: '.ant-table-row',
    animation: 150,
    ghostClass: 'blue-background-class',
    forceFallback: true,
    sort: true,
    // async
    onEnd(item) {
      console.log({ item })
      if (item.newIndex === item.oldIndex) return
      const startIndex = (item.oldIndex as number) - 1
      const endIndex = (item.newIndex as number) - 1
      const { id } = tableData.value[startIndex]
      const { order } = tableData.value[endIndex]
      sortFunc({ id, order })
    }
  })
}
onMounted(() => initSortable())
</script>

<style lang="less" scoped>
.operation-bar {
  .ant-btn-link {
    padding: 4px 0px;
  }
}
</style>
